<template>
  <scroll-view
    enable-back-to-top
    scroll-y
    class="customer"
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="getOpportunityList"
  >
    <view style="margin-top: 20rpx" v-for="(row, index) in opportunityList" :key="index">
      <view style="border: 1rpx solid #d7d7d7; border-radius: 5rpx; padding: 20rpx">
        <up-row>
          <up-col span="8">
            <view style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis">{{
              row.name
            }}</view>
          </up-col>
          <up-col span="4">
            <up-row v-if="row?.loginData">
              <up-col span="6">
                <view style="color: #3775cb" @click="handleEdit(row)">编辑</view>
              </up-col>
              <up-col span="6">
                <view style="text-align: right; color: red" @click="handleRemove(row)"> 删除 </view>
                <u-modal
                  :show="showRemoveConfirm"
                  @confirm="handleConfirmRemove"
                  ref="uModal"
                  :asyncClose="true"
                ></u-modal>
              </up-col>
            </up-row>
          </up-col>
        </up-row>
        <up-row>
          <up-col span="3">
            <view style="color: #3775cb">
              {{ row?.saleStageLabel }}
            </view>
          </up-col>
          <up-col span="3">
            <view>
              {{ row?.needAmount }}
            </view>
          </up-col>
          <up-col span="6">
            <view style="text-align: right">
              {{ row?.predictMakeTime }}
            </view>
          </up-col>
        </up-row>
        <view>
          <u-line></u-line>
          <view>
            <view class="cart-list">
              <uni-swipe-action>
                <uni-swipe-action-item
                  v-for="item in row.productItemList"
                  :key="item.productItemId"
                  class="cart-swipe"
                >
                  <!-- 商品信息 -->
                  <view class="goods">
                    <view class="navigator">
                      <image mode="aspectFill" class="picture" :src="item.imageUrl"></image>
                      <view class="meta">
                        <view class="name ellipsis">{{ item?.productName }}</view>
                        <view class="attrsText ellipsis">{{ item?.sku }}</view>
                        <view class="price">{{ item?.nowPrice }}</view>
                      </view>
                    </view>
                    <view class="count"> x {{ item.qty }} </view>
                  </view>
                </uni-swipe-action-item>
              </uni-swipe-action>
            </view>
          </view>
        </view>
      </view>
    </view>
    <u-empty v-show="isFinish && opportunityList.length === 0" mode="history" />
    <u-loadmore v-if="isLoading" status="loading" />
    <u-loadmore v-if="isFinish && opportunityList.length > 0" status="nomore" />
    <view
      @click="openAdd"
      style="
        position: fixed;
        width: 80rpx;
        height: 80rpx;
        background-color: rgba(55, 117, 203, 0.47);
        bottom: 350rpx;
        right: 0;
        border-radius: 50rpx 0 0 50rpx;
        padding: 12rpx 15rpx;
      "
    >
      <u-icon name="plus-circle" color="#3775cb" size="30"></u-icon>
    </view>
  </scroll-view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { deleteOpportunityAPI, getOpportunityListAPI } from '@/services/opportunity'

const props = defineProps<{
  customerId: string
}>()
// 请求参数
const queryParams = ref<any>({
  customerId: props.customerId,
  pageNum: 1,
  pageSize: 10,
})
const showRemoveConfirm = ref(false)
const isFinish = ref(false)
// 是否触发下拉刷新
const isTriggered = ref(false)
// 获取订单列表
const opportunityList = ref<any[]>([])
// 是否加载中标记，用于防止滚动触底触发多次请求
const isLoading = ref(false)
// 自定义下拉刷新被触发
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = true
  // 重置数据
  queryParams.value.page = 1
  opportunityList.value = []
  isFinish.value = false
  // 加载数据
  await getOpportunityList()
  // 关闭动画
  isTriggered.value = false
}
const getOpportunityList = async () => {
  // 如果数据出于加载中，退出函数
  if (isLoading.value) return
  // 退出分页判断
  if (isFinish.value === true) {
    return
  }
  // 发送请求前，标记为加载中
  isLoading.value = true
  // 发送请求
  const res = await getOpportunityListAPI(queryParams.value)
  // 发送请求后，重置标记
  isLoading.value = false
  // 数组追加
  opportunityList.value.push(...res.rows)
  // 分页条件
  if (opportunityList.value.length < res.total) {
    // 页码累加
    queryParams.value.pageNum++
  } else {
    // 分页已结束
    isFinish.value = true
  }
}

const openAdd = async () => {
  uni.navigateTo({
    url:
      '/pagesCustomer/opportunity/opportunityForm?fromPage=customerDetails&customerId=' +
      props.customerId,
  })
}

const handleEdit = async (row: any) => {
  uni.navigateTo({
    url:
      '/pagesCustomer/opportunity/opportunityForm?fromPage=customerDetails&customerId=' +
      props.customerId +
      '&opportunityId=' +
      row?.opportunityId,
  })
}

const handleRemove = async (row: any) => {
  uni.showModal({
    content: '是否删除',
    confirmColor: '#e51010',
    success: async (res) => {
      if (res.confirm) {
        await deleteOpportunityAPI(row.opportunityId)
        opportunityList.value = opportunityList.value.filter(
          (item) => item?.opportunityId !== row.opportunityId,
        )
      }
    },
  })
}

const handleConfirmRemove = async (row: any) => {}

const refreshOpportunityList = async (query: any) => {
  let total: number
  let list: any[]
  if (query.opportunityId) {
    const res = await getOpportunityListAPI({
      opportunityId: query.opportunityId,
      pageNum: 1,
      pageSize: 1,
    })
    total = res.total
    list = []
    for (const j in opportunityList.value) {
      let item: any = opportunityList.value[j]
      for (const i in res.rows) {
        if (opportunityList.value[j]['opportunityId'] === res.rows[i]['opportunityId']) {
          item = res.rows[i]
        }
      }
      list.push(item)
    }
  } else {
    const res = await getOpportunityListAPI(queryParams.value)
    total = res.total
    list = JSON.parse(JSON.stringify(opportunityList.value))
    for (const j in res.rows) {
      let inD = false
      for (const i in opportunityList.value) {
        if (opportunityList.value[i]['opportunityId'] === res.rows[j]['opportunityId']) {
          inD = true
        }
      }
      if (!inD) {
        list.push(res.rows[j])
      }
    }
  }
  opportunityList.value = JSON.parse(JSON.stringify(list))
  if (opportunityList.value.length < total) {
    isFinish.value = false
  }
}
// 组件挂载完毕
onMounted(() => {
  getOpportunityList()
})
// 暴露
defineExpose({
  refreshOpportunityList,
})
</script>

<style scoped lang="scss">
// 购物车列表
.cart-list {
  padding: 0 20rpx;

  // 优惠提示
  .tips {
    display: flex;
    align-items: center;
    line-height: 1;
    margin: 30rpx 10rpx;
    font-size: 26rpx;
    color: #666;

    .label {
      color: #27ba9b;
      padding: 7rpx 15rpx 5rpx;
      border-radius: 4rpx;
      font-size: 24rpx;
    }
  }

  // 购物车商品
  .goods {
    display: flex;
    padding: 20rpx 0;
    border-radius: 10rpx;
    background-color: #fff;
    position: relative;

    .navigator {
      display: flex;
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 20rpx;
    }

    .name {
      height: 82rpx;
      font-size: 26rpx;
      color: #444;
    }

    .attrsText {
      line-height: 1.8;
      padding: 0 15rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
    }

    .price {
      line-height: 1;
      font-size: 26rpx;
      margin-bottom: 2rpx;
      color: #cf4444;

      &::before {
        content: '￥';
        font-size: 80%;
      }
    }

    // 商品数量
    .count {
      position: absolute;
      bottom: 10rpx;
      right: -20rpx;

      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 220rpx;
      height: 48rpx;

      .text {
        height: 100%;
        padding: 0 20rpx;
        font-size: 32rpx;
        color: #444;
      }

      .input {
        height: 100%;
        text-align: center;
        border-radius: 4rpx;
        font-size: 24rpx;
        color: #444;
        background-color: #f6f6f6;
      }
    }
  }

  .cart-swipe {
    display: block;
    margin: 20rpx 0;
  }

  .cart-swipe-right {
    display: flex;
    height: 100%;

    .button {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 50px;
      padding: 6px;
      line-height: 1.5;
      color: #fff;
      font-size: 26rpx;
      border-radius: 0;
    }

    .delete-button {
      background-color: #cf4444;
    }
  }
}
</style>
